/**
 * 鼠标事件处理工具函数
 */
import { getCanvasCoordinates, projectPointOnLine } from '../expressionUtils';
import { findClickedPoint, findClickedLine, findClickedPerpendicular, getDistance } from '../canvasUtils';

/**
 * 获取画布坐标
 */
export function getCanvasCoords(e) {
  const canvas = e.target;
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  return { x, y };
}

/**
 * 处理点击点
 */
export function handlePointClick(coords, geometryData, currentTool) {
  const clickedPoint = findClickedPoint(coords, geometryData.points);
  
  if (clickedPoint) {
    return {
      type: 'point',
      item: clickedPoint
    };
  }
  
  return null;
}

/**
 * 处理点击线段
 */
export function handleLineClick(coords, geometryData) {
  const clickedLine = findClickedLine(coords, geometryData.points, geometryData.lines);
  
  if (clickedLine) {
    return {
      type: 'line',
      item: clickedLine
    };
  }
  
  return null;
}

/**
 * 处理点击垂线
 */
export function handlePerpendicularClick(coords, geometryData) {
  const clickedPerp = findClickedPerpendicular(coords, geometryData.points, geometryData.perpendiculars);
  
  if (clickedPerp) {
    return {
      type: 'perpendicular',
      item: clickedPerp
    };
  }
  
  return null;
}

/**
 * 在线段上添加点
 */
export function addPointOnLine(coords, line, lineStart, lineEnd, pointOnLineMode) {
  // 计算点击位置在线段上的投影
  const lineLength = getDistance(lineStart, lineEnd);
  const t = Math.max(0, Math.min(1,
    ((coords.x - lineStart.x) * (lineEnd.x - lineStart.x) +
      (coords.y - lineStart.y) * (lineEnd.y - lineStart.y)) / (lineLength * lineLength)
  ));

  const projectionX = lineStart.x + t * (lineEnd.x - lineStart.x);
  const projectionY = lineStart.y + t * (lineEnd.y - lineStart.y);

  // 创建新点
  const newPoint = {
    id: `point_${Date.now()}`,
    x: projectionX,
    y: projectionY,
    label: '',
    color: '#007AFF',
    draggable: true
  };

  return {
    point: newPoint,
    t: t
  };
}

/**
 * 检查是否点击了某个元素
 */
export function findClickedElement(coords, geometryData) {
  // 优先检查点
  const point = findClickedPoint(coords, geometryData.points);
  if (point) {
    return { type: 'point', item: point };
  }

  // 检查线段
  const line = findClickedLine(coords, geometryData.points, geometryData.lines);
  if (line) {
    return { type: 'line', item: line };
  }

  // 检查垂线
  const perp = findClickedPerpendicular(coords, geometryData.points, geometryData.perpendiculars);
  if (perp) {
    return { type: 'perpendicular', item: perp };
  }

  return null;
}

